/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.logiclander.whozwho.web.rest;

import static com.google.common.base.Predicates.notNull;

import java.util.List;

import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;

import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.logiclander.whozwho.core.types.DescriptiveLink;
import com.logiclander.whozwho.core.types.ObjectFactory;
import com.logiclander.whozwho.core.types.SystemType;
import com.logiclander.whozwho.core.types.SystemsType;
import com.logiclander.whozwho.data.dao.SystemDto;
import com.sun.xml.bind.v2.TODO;

/**
 * 
 * @author logiclander
 */
public class JaxbTypesFactory {

	private JaxbTypesFactory() {
		// No instances needed for static factories.
	}

	public static SystemType createSystemTypeFromSystemDto(UriInfo uriInfo,
			SystemDto s) {

		ObjectFactory factory = new ObjectFactory();
		SystemType t = factory.createSystemType();

		t.setId(s.getSid());

		if (notNull().apply(s.getTitle())) {
			t.setTitle(s.getTitle());
		}

		return t;
	}

	public static SystemsType createSystemsTypeFromSystemDtoCollection(
			UriInfo uriInfo, List<SystemDto> systemDtos) {

		ObjectFactory factory = new ObjectFactory();
		SystemsType systemsType = factory.createSystemsType();

		List<DescriptiveLink> descriptiveLinks = Lists.transform(systemDtos,
				toDescriptiveLink(uriInfo));

		List<DescriptiveLink> systemTypes = systemsType.getSystem();
		systemTypes.addAll(descriptiveLinks);

		return systemsType;
	}

	private static Function<SystemDto, DescriptiveLink> toDescriptiveLink(
			final UriInfo uriInfo) {

		return new Function<SystemDto, DescriptiveLink>() {

			ObjectFactory factory = new ObjectFactory();

			@Override
			public DescriptiveLink apply(SystemDto input) {
				DescriptiveLink descriptiveLink = 
						factory.createDescriptiveLink();
				descriptiveLink.setId(input.getSid().toString());
				setHref(descriptiveLink, input.getSid());
				return descriptiveLink;
			}
			
			private void setHref(DescriptiveLink descriptiveLink, Long sid) {
				UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
				uriBuilder.path(SystemController.class);
				uriBuilder.path("system");
				uriBuilder.path(sid.toString());
				
				descriptiveLink.setHref(uriBuilder.build().toASCIIString());
			}
		};
	}
}
